<template>
  <Dialog :title="dialogTitle" v-model="dialogVisible">
    <el-form
      ref="formRef"
      :model="formData"
      :rules="formRules"
      label-width="100px"
      v-loading="formLoading"
      width="65%"
      :disabled="readonlyFlag"
    >
      <el-row>
        <el-col :span="12">
          <el-form-item label="发票编号" prop="code">
            <el-input v-model="formData.code" placeholder="请输入发票编号" />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="客户名称" prop="customerId">
            <el-select
              v-model="formData.customerId"
              class="w-1/1"
              filterable
              placeholder="请选择客户"
              @change="handleCustomerChange"
            >
              <el-option
                v-for="item in customerList"
                :key="item.id"
                :label="item.name"
                :value="item.id"
              />
            </el-select>
          </el-form-item>
        </el-col>
      </el-row>
      <el-row>
        <el-col :span="12">
          <el-form-item label="合同编号" prop="contractId">
            <el-select
              v-model="formData.contractId"
              :disabled="formType !== 'create' || !formData.customerId"
              class="w-1/1"
              filterable
              placeholder="请选择合同"
              @change="handleContractChange"
            >
              <el-option
                v-for="data in contractList"
                :key="data.id"
                :disabled="data.auditStatus !== 20"
                :label="data.name"
                :value="data.id!"
              />
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="开票金额" prop="receiptAmount">
            <el-input v-model="formData.receiptAmount" placeholder="请输入开票金额" />
          </el-form-item>
        </el-col>
      </el-row>
      <el-row>
        <el-col :span="12">
          <el-form-item label="开票日期" prop="receiptDate">
            <el-date-picker
              v-model="formData.receiptDate"
              type="date"
              value-format="x"
              format="YYYY-MM-DD"
              placeholder="选择开票日期"
              style="width: 100%"
            />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="开票类型" prop="receiptType">
            <el-select v-model="formData.receiptType" placeholder="请选择开票类型" class="w-1/1">
              <el-option
                v-for="dict in getStrDictOptions(DICT_TYPE.CRM_RECEIPT_TYPE)"
                :key="dict.value"
                :label="dict.label"
                :value="dict.value"
              />
            </el-select>
          </el-form-item>
        </el-col>
      </el-row>
      <el-row>
        <el-col :span="12">
          <el-form-item label="开票状态" prop="status">
            <el-select v-model="formData.status" placeholder="请选择开票状态" class="w-1/1">
              <el-option
                v-for="dict in getStrDictOptions(DICT_TYPE.CRM_RECEIPT_STATUS)"
                :key="dict.value"
                :label="dict.label"
                :value="dict.value"
              />
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="负责人" prop="ownerUserId">
            <el-select
              v-model="formData.ownerUserId"
              :disabled="formType !== 'create'"
              class="w-1/1"
            >
              <el-option
                v-for="item in userOptions"
                :key="item.id"
                :label="item.nickname"
                :value="item.id"
              />
            </el-select>
          </el-form-item>
        </el-col>
      </el-row>
      <el-row>
        <el-col :span="12">
          <el-form-item label="发票抬头" prop="titleId">
            <el-select v-model="formData.titleId" placeholder="请选发票抬头" class="w-1/1">
              <el-option
                v-for="item in receiptTitleList"
                :key="item.id"
                :label="item.title"
                :value="item.id"
              />
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="开票内容" prop="remark">
            <el-input v-model="formData.content" placeholder="请输入开票内容" />
          </el-form-item>
        </el-col>
      </el-row>
      <el-row>
        <el-col :span="24">
          <el-form-item label="备注" prop="remark">
            <el-input type="textarea" v-model="formData.remark" placeholder="请输入备注" />
          </el-form-item>
        </el-col>
      </el-row>
    </el-form>
    <template #footer>
      <el-button @click="submitForm" type="primary" :disabled="formLoading" v-show="!readonlyFlag"
        >确 定</el-button
      >
      <el-button @click="((dialogVisible = false), (readonlyFlag = true))">取 消</el-button>
    </template>
  </Dialog>
</template>
<script setup lang="ts">
import { DICT_TYPE, getIntDictOptions, getStrDictOptions } from '@/utils/dict'
import { ReceiptApi, Receipt } from '@/api/crm/receipt'
import * as UserApi from '@/api/system/user'
import { useUserStore } from '@/store/modules/user'
import * as ReceiptTitleApi from '@/api/crm/receipttitle'
import * as CustomerApi from '@/api/crm/customer'
import * as ContractApi from '@/api/crm/contract'

/** crm发票管理 表单 */
defineOptions({ name: 'ReceiptForm' })

const props = defineProps<{
  customerId: number
  contractId: number
}>()

const { t } = useI18n() // 国际化
const message = useMessage() // 消息弹窗

const dialogVisible = ref(false) // 弹窗的是否展示
const dialogTitle = ref('') // 弹窗的标题
const formLoading = ref(false) // 表单的加载中：1）修改时的数据加载；2）提交的按钮禁用
const formType = ref('') // 表单的类型：create - 新增；update - 修改
const formData = ref({
  id: undefined,
  code: undefined,
  customerId: undefined,
  customerName: undefined,
  contractId: undefined,
  contractName: undefined,
  receiptAmount: undefined,
  receiptDate: undefined,
  receiptType: undefined,
  content: undefined,
  titleId: undefined,
  status: undefined,
  processInstanceId: undefined,
  auditStatus: undefined,
  remark: undefined,
  ownerUserId: undefined
})
const formRules = reactive({})
const formRef = ref() // 表单 Ref

const userOptions = ref<UserApi.UserVO[]>([]) // 用户列表
const receiptTitleList = ref<ReceiptTitleApi.ReceiptTitle[]>([])
const customerList = ref<CustomerApi.CustomerVO[]>([]) // 客户列表
const contractList = ref<ContractApi.ContractVO[]>([]) // 合同列表

// 只读开关
const readonlyFlag = ref(true)

/** 打开弹窗 */
const open = async (type: string, id?: number, customerId?: number, contractId?: number) => {
  readonlyFlag.value = type == 'detail'
  dialogVisible.value = true
  dialogTitle.value = t('action.' + type)
  formType.value = type
  resetForm()

  // 获得用户列表
  userOptions.value = await UserApi.getSimpleUserList()
  // 获取发票抬头列表
  if (customerId !== undefined) {
    receiptTitleList.value = await ReceiptTitleApi.getReceiptTitleList(customerId)
  }

  // 获得客户列表
  customerList.value = await CustomerApi.getCustomerSimpleList()

  // 默认新建时选中自己
  if (formType.value === 'create') {
    formData.value.ownerUserId = useUserStore().getUser.id
  }
  if (customerId !== undefined) {
    formData.value.customerId = customerId
    contractList.value = await ContractApi.getContractSimpleList(customerId)
  }

  // 修改时，设置数据
  if (id) {
    formLoading.value = true
    try {
      const data = await ReceiptApi.getReceipt(id)
      formData.value = data
      await handleCustomerChange(data.customerId!)
      formData.value.contractId = data?.contract?.id
    } finally {
      formLoading.value = false
    }
  }

  // 修改时，设置数据
  if (id) {
    formLoading.value = true
    try {
      formData.value = await ReceiptApi.getReceipt(id)
    } finally {
      formLoading.value = false
    }
  }
}
defineExpose({ open }) // 提供 open 方法，用于打开弹窗

/** 提交表单 */
const emit = defineEmits(['success']) // 定义 success 事件，用于操作成功后的回调
const submitForm = async () => {
  // 校验表单
  await formRef.value.validate()
  // 提交请求
  formLoading.value = true
  try {
    const data = formData.value as unknown as Receipt
    if (formType.value === 'create') {
      await ReceiptApi.createReceipt(data)
      message.success(t('common.createSuccess'))
    } else {
      await ReceiptApi.updateReceipt(data)
      message.success(t('common.updateSuccess'))
    }
    dialogVisible.value = false
    // 发送操作成功的事件
    emit('success')
  } finally {
    formLoading.value = false
  }
}

/** 重置表单 */
const resetForm = () => {
  formData.value = {
    id: undefined,
    code: undefined,
    customerId: undefined,
    customerName: undefined,
    contractId: undefined,
    contractName: undefined,
    receiptAmount: undefined,
    receiptDate: undefined,
    receiptType: undefined,
    content: undefined,
    titleId: undefined,
    status: undefined,
    processInstanceId: undefined,
    auditStatus: undefined,
    remark: undefined,
    ownerUserId: undefined
  }
  formRef.value?.resetFields()
}

/** 处理切换客户 */
const handleCustomerChange = async (customerId: number) => {
  const selectedOption = customerList.value.find((item: any) => {
    return item.id === customerId
  }) as CustomerApi.CustomerVO
  // 重置合同编号
  formData.value.contractId = undefined
  formData.value.customerName = selectedOption.name
  // 获得合同列表
  if (selectedOption.id) {
    contractList.value = []
    contractList.value = await ContractApi.getContractSimpleList(selectedOption.id)
    // 刷新发票抬头列表
    receiptTitleList.value = await ReceiptTitleApi.getReceiptTitleList(selectedOption.id)
  }
}

/** 处理切换客户 */
const handleContractChange = async (contractId: number) => {
  const selectedOption = contractList.value.find((item: any) => {
    return item.id === contractId
  }) as ContractApi.ContractVO
  // 重置合同编号
  formData.value.contractName = selectedOption.name
}
</script>
